import {Line} from './line.js'
import {Ball} from './ball.js'
import {captureMouse} from './untils.js'

window.onload = ()=>{
    let canvas = document.getElementById('canvas')
    let ctx = canvas.getContext('2d')
    canvas.width = window.innerWidth
    canvas.height = window.innerHeight
    let ball = new Ball({ctx, radius: 20})
    let line = new Line({sx : 0, ey: 300, ex: 800, ctx})
    let gravity = 0.2 //重力加速度
    let bounce = -0.6 //反弹系数
    let angleN = 0 //斜面旋转角度
    ball.x = 100
    ball.y = 50
    line.x = 100
    line.y = 150
    line.rotation = angleN
    let mouse = captureMouse(canvas)
    ;(function update(){
        requestAnimationFrame(update, canvas)
        ctx.clearRect(0, 0, canvas.width, canvas.height)
        line.setEY(mouse.y - line.y)
        ball.vy += gravity //根据重力下降
        ball.x += ball.vx
        ball.y += ball.vy

        if(ball.x + ball.radius > canvas.width || ball.x - ball.radius < 0){//x边界反弹
            ball.vx *= bounce
        }

        if(ball.y + ball.radius > canvas.height ){//y边界反弹
            ball.vy *= bounce
            ball.vy = -Math.abs(ball.vy) - gravity
        }

        let cos = Math.cos(line.rotation)
        let sin = Math.sin(line.rotation)
        let lx = ball.x - (line.x + line.sx)
        let ly = ball.y - (line.y + line.sy)
        let rx = lx * cos + ly * sin
        let ry = ly * cos - lx * sin
        let rect = line.getRect()
        if(ball.x + ball.radius > rect.sx && ball.x - ball.radius < rect.ex && -ry < rect.ey){
            if(ry > -ball.radius){//球撞到了线
                //转到, 线是平面的坐标系下面
                let vx = ball.vx * cos + ball.vy * sin
                let vy = ball.vy * cos - ball.vx * sin

                ry = -ball.radius
                vy *= bounce//反弹
                
                lx = rx * cos - ry * sin    //公式变化了
                ly = ry * cos + rx * sin
                ball.x = line.x + lx + line.sx
                ball.y = line.y + ly + line.sy
                //转回真实坐标系
                ball.vx = vx * cos - vy * sin
                ball.vy = vy * cos + vx * sin
            }
        }
        line.draw()
        ball.draw()
    })()
}